package cn.vq3.kmsaiserver.kmsaiserver.service.Impl;

import cn.vq3.kmsaiserver.kmsaiserver.pojo.sendMessageEntity;
import cn.vq3.kmsaiserver.kmsaiserver.service.forwardMessageService;
import cn.vq3.kmsaiserver.kmsaiserver.utils.loadProperties;
import cn.vq3.kmsaiserver.kmsaiserver.utils.sendParameterAssembled;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import okhttp3.*;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

@Service
public class forwardMessageServiceImpl implements forwardMessageService {

    @Autowired
    sendParameterAssembled sendParameterAssembled;

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    loadProperties loadProperties;

    static Logger logger = Logger.getLogger("KmsAiServerApplication.class");
    public static final String API_KEY = "WrPSgedTvYcOdS6Nbj6kkHKj";
    public static final String SECRET_KEY = "T5TYdZpeFg4nWDmlrHvgksznsrL1E58R";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Override
    public com.alibaba.fastjson2.JSONObject sendMessage(com.alibaba.fastjson2.JSONObject message) throws IOException {
        File directory = new File("");

        //IDEA  跑用这个
        //String path = directory.getCanonicalPath()+"\\src\\main\\resources\\sendSettingData.yaml";

        // 服务器跑用这个
        String path = directory.getCanonicalPath()+"/ERNIEBotParmeterData.yaml";
        Map<String, Object> stringObjectMap = loadProperties.loadProperties(path);

        String useVersion = (String)stringObjectMap.get("use_version");
        String useApi = (String)stringObjectMap.get(useVersion);

        sendMessageEntity sendMessageEntity = sendParameterAssembled.sendParameterAssembled();

        // 设置为配置文件内的参数  开始
        message.put("top_p",sendMessageEntity.getTop_p());
        message.put("enable_citation",sendMessageEntity.isEnable_citation());
        message.put("penalty_score",sendMessageEntity.getPenalty_score());
        message.put("temperature",sendMessageEntity.getTemperature());
        message.put("disable_search",sendMessageEntity.isDisable_search());
        message.put("user_id",sendMessageEntity.getUser_id());
        message.put("system",sendMessageEntity.getSystem());
        message.put("stop",sendMessageEntity.getStop());
        message.put("max_output_tokens",sendMessageEntity.getMax_output_tokens());
        message.put("response_format",sendMessageEntity.getResponse_format());
        // 设置为配置文件内的参数  结束


        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, String.valueOf(message));
        Request request = new Request.Builder()
                .url(useApi + "?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string = response.body().string();
        com.alibaba.fastjson2.JSONObject jsonObject = JSON.parseObject(string);
        String assistantResult = (String)jsonObject.get("result");

        JSONArray messages = (JSONArray)message.get("messages");
        com.alibaba.fastjson2.JSONObject jsonObject1 = new com.alibaba.fastjson2.JSONObject();
        jsonObject1.put("role","assistant");
        jsonObject1.put("content",assistantResult);
        messages.add(jsonObject1);
        message.put("messages",messages);

        return message;

    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }


}
